<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AK JOB</title>
    <link rel="icon" type="image/x-icon" href="../../../layuiadmin/style/res/favicon.png"/>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../../../layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../../layuiadmin/style/admin.css" media="all">
    <style>
        .menu-box {
            width: 48%;
            position: absolute;
            left: 51%;
            top: 15px;
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card layui-padding-3" style="width: 50%">
        <div class="layui-card-header">角色信息</div>
        <div class="layui-card-body">
            <div class="layui-form" lay-filter="roleForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">角色名称</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="id" value="">
                        <input type="text" name="roleName" lay-verify="required" placeholder="请输入角色名称"
                               autocomplete="off"
                               lay-verType="tips"
                               class="layui-input"/>
                    </div>
                </div>
                <input type="button" class="layui-btn layui-hide" style="width: 100%" lay-submit
                       lay-filter="roleFormSubmit"
                       id="roleFormSubmit" value="保存">
            </div>
        </div>
    </div>


    <div class="layui-card menu-box">
        <div class="layui-card-header">选择菜单及权限</div>
        <div class="layui-card-body">
            <div id="menuTree"></div>
        </div>
    </div>
</div>

<script src="../../../layuiadmin/layui/layui.js"></script>
<script src="../../../layuiadmin/lib/juicer-min.js"></script>

<script type="text/html" id="roleForm">

</script>
<script>
    layui.config({
        base: '../../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'roles', 'table', 'setter', 'auth', 'treeMenu', 'menus', 'roles', 'AppHelper'], function () {
        var $ = layui.$
            , form = layui.form
            , roles = layui.roles
            , setter = layui.setter
            , table = layui.table
            , treeMenu = layui.treeMenu
            , menus = layui.menus
            , tm = null
            , roles = layui.roles
            , AppHelper = layui.AppHelper
            , LayerPage = AppHelper.getLayerPage()
            , checkedMenus = []
        ;

        var queryAllMenus = function (menu, all) {
            $.each(all, function (index, item) {
                if (item.children) {
                    checkedMenus = checkedMenus.concat(item.children);
                    queryAllMenus(item, item.children);
                } else {
                    checkedMenus.push(item);
                }
            })
        }

        var loadMenusAndFeatures = function (menus, features, currentRole) {
            $.each(menus, function (index, item) {
                item.name = item.menuName;
                item.nodeType = "menu";
            });

            var viewableFeature = [];
            $.each(features, function (index, item) {
                //如果功能没有被菜单绑定则忽略
                if (item.menuId) {
                    item.name = item.featureAlias;
                    item.parentId = item.menuId;
                    item.nodeType = "feature";

                    viewableFeature.push(item);
                }
            })

            if (currentRole) {
                var root = currentRole.menus;
                var checkedFeatures = [];

                //查询所有菜单
                checkedMenus = checkedMenus.concat(root);
                $.each(root, function (index, item) {
                    queryAllMenus(item, item.children);
                })

                $.each(checkedMenus, function (index, item) {
                    if (item.features && item.features.length > 0) {
                        checkedFeatures = checkedFeatures.concat(item.features);
                    }
                })

                for (var mi = 0; mi < checkedMenus.length; mi++) {
                    for (var mj = 0; mj < menus.length; mj++) {
                        if (checkedMenus[mi].id == menus[mj].id) {
                            menus[mj].checked = true;
                        }
                    }
                }

                for (var pi = 0; pi < checkedFeatures.length; pi++) {
                    for (var pj = 0; pj < features.length; pj++) {
                        if (checkedFeatures[pi].id == features[pj].id) {
                            features[pj].checked = true;
                        }
                    }
                }
            }

            var data = menus.concat(viewableFeature);

            tm = treeMenu.customRender({
                elem: "#menuTree"
                , nodes: data
                , edit: {
                    showToolBar: false
                    , remove: false
                }
                , treeConfig: {
                    data: {
                        simpleData: {
                            enable: true
                            , pIdKey: "parentId"
                        }
                    }
                    , check: {
                        enable: true
                    }
                }
            });

            //展开所有
            tm.expandAll(true);
        }


        //获取执行动作
        var router = layui.router();
        var action = router.search.action;
        var id = router.search.id;

        var checkMenus = function () {
            var nodes = tm.getCheckedNodes();
            if (nodes.length == 0) {
                layer.msg("您还未选择菜单和功能!", {icon: 0});
                return false;
            }
            return true;
        }

        var injectRole = function (role) {
            var nodes = tm.getCheckedNodes();
            var menuFeatures = [];
            var menuIds = [];
            $.each(nodes, function (index, item) {
                var menuFeature = {};
                var nodeType = item.nodeType;

                switch (nodeType) {
                    case "feature":
                        menuFeature.featureId = item.id;
                        menuFeature.menuId = item.menuId;
                        menuFeatures.push(menuFeature);
                        break;
                    case "menu":
                        menuIds.push(item.id);
                        break;
                }
            })

            role.checkedMenuFeature = {menuFeatures: menuFeatures, menuIds: menuIds};
            return role;
        }

        //关闭当前iframe
        // var closeSelf = function () {
        //     var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        //     parent.layer.close(index); //再执行关
        // }

        //刷新表格
        var refreshParentTable = function () {
            parent.layui.table.reload("LAY-role-manage");
        }

        //如果是新增动作
        switch (action) {
            case "add":
                //加载权限和菜单
                var loadIndex = layer.load(2);
                $.when(menus.methods.all(), menus.methods.allFeatures())
                    .always(function () {
                        layer.close(loadIndex);
                    })
                    .done(function (mrq, prq) {
                        var menuRes = mrq[0];
                        var featureRes = prq[0];

                        var menus = menuRes.data;
                        var features = featureRes.data;

                        loadMenusAndFeatures(menus, features);

                    })
                //提交表单
                form.on("submit(roleFormSubmit)", function (data) {
                    var newRole = data.field;
                    var isChecked = checkMenus();
                    if (!isChecked) {
                        return;
                    }

                    newRole = injectRole(newRole);
                    var layerPageLoad = LayerPage.load();
                    roles.add(newRole)
                        .done(function (res) {
                            if (res.code == "200") {
                                layerPageLoad.close();
                                parent.layer.msg("保存成功！", {icon: 1}, function () {
                                })
                                refreshParentTable();
                                LayerPage.close();
                            }
                        }).fail(function () {
                            layerPageLoad.close();
                        })
                    return;
                })
                break;
            case "edit":
                //加载权限和菜单
                var loadIndex = layer.load(2);
                $.when(menus.methods.all(), menus.methods.allFeatures(), roles.getFull(id))
                    .always(function () {
                        layer.close(loadIndex);
                    })
                    .done(function (mrq, prq, rrq) {
                        var menuRes = mrq[0];
                        var privilegeRes = prq[0];
                        var currentRoleRes = rrq[0];

                        var menus = menuRes.data;
                        var privileges = privilegeRes.data;
                        var currentRole = currentRoleRes.data;

                        loadMenusAndFeatures(menus, privileges, currentRole);

                        //回显角色名称
                        form.val("roleForm", {
                            "roleName": currentRole.roleName
                            , "id": currentRole.id
                        })

                    })

                form.on("submit(roleFormSubmit)", function (data) {
                    var editRole = data.field;
                    var isChecked = checkMenus();
                    if (!isChecked) {
                        return;
                    }

                    editRole = injectRole(editRole);
                    // var loadIndex = parent.layer.load(2);
                    var layerPageLoad = LayerPage.load();
                    roles.update(editRole)
                        .done(function (res) {
                            if (res.code == "200") {
                                layerPageLoad.close();
                                parent.layer.msg("修改成功！", {icon: 1}, function () {
                                })
                                refreshParentTable();
                                LayerPage.close();
                            }
                        }).fail(function () {
                        layerPageLoad.close();
                    })
                    return;
                })
                break;
        }


    });
</script>
</body>
</html>
